package com.atguigu.springcloud.controller;

import com.atguigu.springcloud.entityes.CommonResult;
import com.atguigu.springcloud.entityes.Payment;
import com.atguigu.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class PaymentController
{
    @Resource
    private PaymentService paymentService;

    @Value("${server.port}")
    private String serverPort;

    @Resource
    private DiscoveryClient discoveryClient;

    @PostMapping(value = "/payment/create")
    public CommonResult create(@RequestBody Payment payment)

    {
        int result = paymentService.create(payment);
        log.info("*****插入结果:" + result);
        if (result>0){
            return new CommonResult(200,"插入数据成功-服务提供者:"+serverPort,result);
        }else{
            return new CommonResult(444,"插入数据失败",null);
        }
    }

    @GetMapping(value = "/payment/get/{id}")
    public CommonResult getPaymentById(@PathVariable("id") long id)
    {
        Payment payment = paymentService.getPaymentById(id);
        log.info("*****查询结果:{}",payment);
        if (payment!=null){
            return new CommonResult(200,"查询成功-服务提供者:"+serverPort,payment);
        }else{
            return new CommonResult(444,"没有对应的记录,查询ID:"+id,null);
        }
    }


    @GetMapping(value = "/payment/discovery")
    public Object discovery()
    {
        List<String> services = discoveryClient.getServices();
        for (String element : services) {
            System.out.println(element);
        }

        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance element  : instances)
        {
            System.out.println(element.getServiceId()+"\t"+element.getHost()+"\t"+
                    element.getPort()+"\t"+element.getUri());
        }

        return this.discoveryClient;
    }


    @GetMapping(value = "/payment/lb")
    public String getPaymentLB()
    {
        return serverPort;
    }

    @GetMapping(value = "/payment/feign/timeout")
    public String paymentFeignTimeOut()
    {
        System.out.println("*****paymentFeignTimeOut from port: "+serverPort);
        //暂停几秒钟线程
        try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); }
        return serverPort;
    }

    @GetMapping("/payment/zipkin")
    public String paymentZipkin()
    {
        return "hi ,i'am paymentzipkin server fall back，welcome to atguigu，O(∩_∩)O哈哈~";
    }

    /**
     * 下载模板
     * @param response
     */
        @RequestMapping("/payment/uploadFile")
        public void downloadFile(HttpServletResponse response) {
            // 文件的存放路径
            ClassPathResource resource = new ClassPathResource("手工外流数据导入模板.xlsx");
            // 通过resource获取流
            try(InputStream inputStream = resource.getInputStream()) {
                response.reset();
                response.setContentType("application/octet-stream");
                String filename = resource.getFilename();
                response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
                ServletOutputStream outputStream = response.getOutputStream();
                byte[] b = new byte[1024];
                int len = 0;
                //从输入流中读取一定数量的字节，并将其存储在缓冲区字节数组中，读到末尾返回-1
                while ((len = inputStream.read(b)) !=-1) {
                    outputStream.write(b, 0, len);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

    }

}
